/*
 * @lc app=leetcode.cn id=109 lang=javascript
 *
 * [109] 有序链表转换二叉搜索树
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {ListNode} head
 * @return {TreeNode}
 */

// 如果不使用数组，可以使用快慢指针查找链表的中位节点
function buildTree(arr, l, r) {
  if(l > r) return null;
  let mid = l + ((r - l) >> 1);
  let root = new TreeNode(arr[mid]);
  root.left = buildTree(arr, l, mid - 1);
  root.right = buildTree(arr, mid + 1, r);
  return root;
}
var sortedListToBST = function(head) {
  if(!head) return head;
  let p = head, arr = [];
  while(p) {
    arr.push(p.val);
    p = p.next;
  }
  return buildTree(arr, 0, arr.length - 1);
};
// @lc code=end

